package com.basic.ui.view

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.Button
import android.widget.FrameLayout
import android.widget.TextView
import androidx.core.view.isVisible
import com.basic.ui.R
import com.basic.ui.utils.setOnClick

/**
 * 显示错误态，空态，loading 态， 各种状态是懒加载的
 *
 * @author: Peter Liu
 * @date: 2022/11/9
 *
 */
class StateView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr), IStateView {
    private var errorGroupView: View? = null
    private var emptyGroupView: View? = null
    private var loadingGroupView: View? = null

    private var tvErrorDesc: TextView? = null
    private var tvLoading: TextView? = null
    private var tvEmpty: TextView? = null
    private var btnRetry: Button? = null

    private var onRetry: OnViewClick? = null

    override fun showError(msg: String?, code: String?) {
        this.isVisible = true
        emptyGroupView?.gone()
        loadingGroupView?.gone()
        if (errorGroupView == null) {
            errorGroupView = inflate(R.layout.basic_ui_layout_state_error, false)
            tvErrorDesc = errorGroupView?.findViewById(R.id.tvErorrDesc)
            btnRetry = errorGroupView?.findViewById(R.id.btnRetry)
            if (this.onRetry != null) {
                btnRetry?.setOnClick(onClick = this.onRetry!!)
            }
            add(errorGroupView!!)
        }
        errorGroupView?.isVisible = true
        tvErrorDesc?.text = msg
    }

    override fun showLoading(show: Boolean, msg: String?) {
        if (show) {
            this.isVisible = true
            errorGroupView?.gone()
            emptyGroupView?.gone()
            if (loadingGroupView == null) {
                loadingGroupView = inflate(R.layout.basic_ui_layout_state_loading, false)
                tvLoading = loadingGroupView?.findViewById(R.id.tvLoading)
                add(loadingGroupView!!)
            }
            loadingGroupView?.isVisible = true
            tvLoading?.text = msg
        } else {
            loadingGroupView?.gone()
        }
    }

    override fun showEmpty(msg: String?) {
        this.isVisible = true
        errorGroupView?.gone()
        loadingGroupView?.gone()
        if (emptyGroupView == null) {
            emptyGroupView = inflate(R.layout.basic_ui_layout_state_empty, false)
            tvEmpty = emptyGroupView?.findViewById(R.id.tvEmpty)
            add(emptyGroupView!!)
        }
        emptyGroupView?.isVisible = true
        tvEmpty?.text = msg
    }

    override fun showNormal() {
        this.gone()
    }

    fun setRetry(onViewClick: OnViewClick) {
        this.onRetry = onViewClick
        if (btnRetry != null) {
            btnRetry?.setOnClick(onClick = onViewClick)
        }
    }
}

